'''
Created on 2014-2-18
author: Quintus
(C)The comments and codes is published under GPL V2
'''
import sys
import os
import re
import subprocess

PARSER_NAME = ''
RULE_NAME = ''
MISMATCH_PATTERN = re.compile('line (\d+):(\d+) (.*) ')
failed_ = []
passed_ = []

def isSyntaxError(record):
    mismatch = []
    for line in record:
        try:
            grouper = MISMATCH_PATTERN.search(line)
            lineNo = grouper.group(1)
            index = grouper.group(2)
            msg = grouper.group(3)
            mismatch.append(line)
        except AttributeError:
            pass
    if len(mismatch) == 0:
        return False, None
    else:
        return True, mismatch
    
def scan(root):
    for currentRoot, dirs, files in os.walk(root):
        for file_ in files:
            if file_.endswith('.ttcn'):
                fileName = os.path.join(currentRoot, file_)
                print '\nFile : %s' % fileName
                os.chdir(currentRoot)
                sub = subprocess.Popen(('grun %s %s %s' % (PARSER_NAME, RULE_NAME, file_)), stdout=None, stderr=subprocess.PIPE, shell=True)
                stdErr = sub.communicate()[1]
                error, messages = isSyntaxError(stdErr.split('\r\n'))
                if error:
                    failed_.append((fileName, messages))
                else:
                    passed_.append(fileName)
            
            
if __name__ == '__main__':
    path = sys.argv[1]
    PARSER_NAME = sys.argv[2]
    RULE_NAME = sys.argv[3]
    scan(path)
    print '\n*********************** Test completed! ***********************\n'
    print 'Failure : ' + str(len(failed_))
    for file_, messages  in failed_:
        print '    ' + file_
        for message in messages:
            print '    ----' + message
    print '\nSuccess : ' + str(len(passed_))
    for file_ in passed_:
        print '    -' + file_
    if len(failed_) == 0:
        sys.exit(0)
        print '\n***********************    Success!    ***********************'
    else:
        print '\n***********************    Failure!    ***********************'
        sys.exit(255)

    
    
    
    
